# Copyright (c) 2009 Daropia Project (www.daropia.org)
#
# This file is part of Daropia and is available under the terms
# of the GNU General Public Licence version 2.0 or later.


# Handle characters operations,
# Mounted on /character



class CharacterController < Controller

	# If no character id given, list all availables characters
	def index
		require_login		
		
		@title = "Gestion des personnages"
		# Select the characters created by the user from the database
		@characters_user = user.characters
	end
	
	
	# Handles character creation
	# Two use case, as always : display a form, and treat it
    def create(user_id)
    
    	require_login
    	
	    if request.post?
	    
	        character = Character.create(
	        							:name => request[:name],
										:signature => request[:signature],
										:avatar => request[:avatar],
										:description => request[:description],
										:gender => request[:gender],
										:address => request[:address],
										:user => user,
										:creation_date => Time.now)
						
			redirect r(:show, character.id)
	    end
	    
		rescue Sequel::DatabaseError => e
        	if e.message == "SQLite3::SQLException: column name is not unique"
        	   	flash[:message] = "Nom de personnage déjà enregistré"
        	end
    end

    # Shows the specified topic
	def show(character_id)
	
		require_login
		
        character = Character[:id => character_id]
        @title = "Fiche personnage de " + character.name
        @name = character.name
        @character = character
    end
    
    
    # Handles character's editing
    def edit (character_id)
    	
    	require_login
    	
    	character = Character[:id => character_id]
    	
    	# If we have parameters then we are in 'edit profile' mode
    	if request.post?

    		# Filling up
			character.address = request['address']
			character.gender = request['gender']
			character.avatar = request['avatar']
			character.description = request['description']
			character.signature = request['signature']

			# Try to save it
			saved = character.save

			if saved
				flash[:message] = "Fiche du personnage modifié"
			else
				flash[:message] = "Erreur lors de la modification de la fiche du personnage"
			end

			# Return to main index
			redirect CharacterController.r(:show, character.id)
			
		else			
	        @name = character.name
	        @character = character
		end

    end


end